package com.luotf.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.luotf.annotation.SystemLog;
import com.luotf.model.Bloger;
import com.luotf.service.BlogerService;
import com.luotf.util.CipherUtil;
import com.luotf.util.ConstantUtil;



@Controller
public class BlogerController {

	@Resource(name = "blogerServiceImpl")
	private BlogerService blogerService;
	
	 /** 
     * 初始登陆界面 
     * @param request 
     * @return 
     */  
    @RequestMapping("/login")  
    public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){  
    	
    	return "login";  
    }  
      
    /** 
     * 验证用户名和密码 
     * @param request 
     * @return 
     */  
    @RequestMapping("/checkLogin")
    @ResponseBody
    @SystemLog(description = ConstantUtil.LOGIN_IN,userType=ConstantUtil.USERTYPE_ADMIN) 
    public Map<String,Object> login(String username,HttpSession session,String password) {  
        //取得 密码，并用MD5加密  
        password = CipherUtil.generatePassword(password);  
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
        Subject currentUser = SecurityUtils.getSubject();  
        Map<String,Object> map = new HashMap<String,Object>();
        try {  
            if (!currentUser.isAuthenticated()){//使用shiro来验证  
                token.setRememberMe(true);  //记住密码
                currentUser.login(token);//验证角色和权限  
            }
            map.put("message", "验证成功");
            map.put("status", 200);
            Bloger bloger = blogerService.findUserByLoginName(username);
            
            session.setAttribute("username", username);
            session.setAttribute("bloger", bloger);
            
        } catch (Exception e) {  
        	map.put("message", "账号或密码错误！");
    		map.put("status", 500);
        }  
        return map;  
    }  
    
    /** 
     * 退出 
     * @return 
     */  
    @RequestMapping(value = "/admin/logout")  
    @SystemLog(description = ConstantUtil.LOGIN_OUT,userType=ConstantUtil.USERTYPE_ADMIN) 
    public void logout(HttpServletRequest request,   HttpServletResponse response) {   
    	String rootpath = request.getServletContext().getContextPath();
    	System.out.println(rootpath);
        Subject currentUser = SecurityUtils.getSubject();    
        currentUser.logout();  
        try {
			response.sendRedirect(rootpath+"/login");
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    
    @RequestMapping(value = "/admin/logout1") 
    @ResponseBody
    @SystemLog(description = ConstantUtil.LOGIN_OUT,userType=ConstantUtil.USERTYPE_ADMIN) 
    public Map<String,Object> logout1(HttpServletRequest request){
    	Map<String,Object> map = new HashMap<String,Object>();
    	String rootpath = request.getServletContext().getContextPath();
        Subject currentUser = SecurityUtils.getSubject();    
        currentUser.logout();  
        map.put("status", 2000);
        map.put("message","安全退出");
    	return map;
    }
    
    /**
     * 
     *@作者:
     *@简介:返回注册页面
     * @return
     */
    @RequestMapping(value="/registered")
	public String getregisteredpage() {
		return "registered";
	}
    
    @RequestMapping(value ="/admin/index")
    public String aaa() {
    	return "admin/index";
    }
	
    /**
     * 
     *@作者:
     *@简介:获取正在登陆的用户
     * @return
     */
    @RequestMapping(value="/getLoggedinuser",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getLoggedinuser(HttpSession session){
    	Map<String,Object> map = new HashMap<String,Object>();
    	Bloger bloger = (Bloger) session.getAttribute("bloger");
    	if(bloger != null) {
    		map.put("status", 2000);
    		map.put("message", "已登录");
    		map.put("resultobj", bloger);
    		return map;
    	}else {
    		map.put("status", 4004);
    		map.put("message", "未登录");
    		return map;
    	}
    }
    
	/**
	 * 
	 *@作者:
	 *@简介:用户注册
	 * @param bloger
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value="",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object>  addbloger(Bloger bloger) {
		Map<String,Object> map = new HashMap<String,Object>();
		Integer row = blogerService.insert(bloger);
		if(row!=null || row != 0) {
			map.put("message", "用户注册成功");
			map.put("status", 200);
			return map;
		}
		map.put("message", "用户注册失败！");
		map.put("status", 500);
		return map;
	}
	
	/**
	 * 
	 *@作者:
	 *@简介:修改账户信息
	 * @return
	 */
	@RequestMapping(value="/selectByPrimaryKey",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> updatebloger(Bloger bloger){
		Map<String,Object> map = new HashMap<String,Object>();
		Integer row = blogerService.updateByPrimaryKey(bloger);
		if(row!=null || row != 0) {
			map.put("message", "修改成功");
			map.put("status", 200);
			return map;
		}
		map.put("message", "修改失败");
		map.put("status", 500);
		return map;
	}
	
	/**
	 * 
	 *@作者:
	 *@简介: 根据id查询用户
	 * @return
	 */
	@RequestMapping(value="/selectByPrimaryKey")
	@ResponseBody
	public Bloger quserBlogerByid(Integer id) {
		Bloger bloger  = blogerService.selectByPrimaryKey(id);
		return bloger;
	}
	
	/**
	 * 
	 *@作者:
	 *@简介: 判断传入的用户名是否重复
	 * @param username
	 * @return
	 */
	@RequestMapping(value="/isRepetitionByName",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> isRepetitionByName(String username){
		Map<String,Object> map = new HashMap<String,Object>();
		Integer countnum = blogerService.countBlogerByname(username);
		if(new Integer(0).equals(countnum)) {
			map.put("message", "success");
			map.put("status", 200);
			return map;
		}
		map.put("message", "error");
		map.put("status", 500);
		return map;
	}
	
	@RequestMapping(value="/addBloger")
	@ResponseBody
	public Map<String,Object> addBloger(Bloger bloger){
		Map<String,Object> map = new HashMap<String,Object>();
		bloger.setHasPermission(0);
		
		Integer row = blogerService.insert(bloger);
		
		if(new Integer(1).equals(row)) {
			
			map.put("message", "用户注册成功");
			map.put("status", 200);
			return map;
		}
		map.put("message", "用户注册失败");
		map.put("status", 500);
		return map;
	}
	
	/**
	 * 
	 *@作者:
	 *@简介:修改头像
	 * @param prarm
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadBlogerphoto", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadBlogerphoto(HttpServletRequest request,HttpSession session) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//获得项目在物理空间的位置（在硬盘的位置）
		String physicspath = session.getServletContext().getRealPath("/");
		System.out.println(physicspath);
		//文件路径
		String filebase = "/images/userphoto/";
		//获得正在登陆的用户
		Bloger bloger = (Bloger) session.getAttribute("bloger");
		//获得旧的文件名
		String oldfilename = bloger.getPhoto().substring(bloger.getPhoto().lastIndexOf('/')+1);
		//旧的文件对象
		File f = new File(physicspath+filebase+oldfilename);
			if(multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
			//获得所有是文件的parameter
			Iterator<String> fileNamesIter = mreq.getFileNames();
			
			while(fileNamesIter.hasNext()) {
				//获得从前台传过来的文件对象
				MultipartFile file = mreq.getFile(fileNamesIter.next());
				
				if (file != null) {
					String myFileName = file.getOriginalFilename();
					if (myFileName.trim() != "") {
						//获得项目根目录
						String contextpath = session.getServletContext().getContextPath();
						//获得原始文件名(带拓展名)
						String fileName = file.getOriginalFilename();
						//获得拓展名
						String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
							//制造文件名避免重名
							SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
							String newFileName = df.format(new Date());
							//新生成的文件名
							String fileNames = newFileName + new Random().nextInt(1000000) + bloger.getId()+"." + fileExt;
						//要上传文件的目录对象=（物理目录+文件路径+新生成的文件名）
						String filePath = physicspath+filebase + fileNames;
						//上传文件在项目中的路径
						String photopath = contextpath+filebase + fileNames;
						//创建要上传文件目录的对象
						File localFile = new File(filePath);
						if (!localFile.exists()) {
							localFile.mkdirs();
						}
						file.transferTo(localFile);
						//修改数据库中的图片路径
						Integer row = blogerService.updateByPrimaryKeySelective(new Bloger(bloger.getId(),null,null,null,null,photopath));
						if(row !=0) {
							map.put("photo", photopath);
							map.put("status", 2000);
							map.put("message", "修改成功");
							
							if(!(new String("/Blog/images/userphoto/photos2.jpg").equals(bloger.getPhoto()))) {
								//修改session中的图片路径
								bloger.setPhoto(photopath);
								//如果旧的文件对象是文件就删除文件
								if(f.isFile()) {
									f.delete();
								}
							}else {
								bloger.setPhoto(photopath);
							}
							
						}else {
							map.put("status", 5000);
							map.put("message", "修改失败");
						}
					}
				}
			}
			
		}
		return map;
	}
    
}
